import {
    fetchDeviceInfo,
    fetchDeviceTrajectory
} from '@/services/device'
import { getParams } from '@/utils/util'
import { customRedirect } from '@/utils/route'
Page({
    data: {
        polygonsPoints: [],
        longitude: null,
        latitude: null,
        readonly: true,
        noticeShow: false
    },
    async onLoad(options) {  
        const { params } = options;
        const { type, device_imei, readonly, polygons } = getParams(params);  
    
        // 设置 readonly 状态  
        this.setData({  
            readonly: !!readonly  
        });  
    
        // 公共函数：设置地图中心点  
        const setMapCenter = async () => {  
            const center = await this.getMapCenter();  
            this.setData({  
                ...center  
            });  
        };  
    
        // 公共函数：解析轨迹点  
        const parseTrajectoryPoints = (data, iconPathStart, iconPathPass) => {  
            return data.map((item, index) => ({  
                id: item.GATHER_UUID || item.id,  
                iconPath: index === 0 ? iconPathStart : iconPathPass,  
                longitude: item.LON || item.ele_fence_precision,  
                latitude: item.LAT || item.ele_fence_latitude,  
                width: 20,  
                height: 20  
            }));  
        };  
    
        // 根据 type 类型执行不同逻辑  
        switch (type) {  
            case 'polyline': {  
                const trackRes = await fetchDeviceTrajectory({ device_imei });  
                const trajectoryData = trackRes?.data || [];  
    
                if (trajectoryData.length === 0) {  
                    await setMapCenter();  
                } else {  
                    this.setData({  
                        longitude: trajectoryData[0].LON,  
                        latitude: trajectoryData[0].LAT,  
                        polyline: [{  
                            points: trajectoryData.map(item => ({  
                                latitude: item.LAT,
                                longitude: item.LON  
                            })),  
                            color: '#000000',  
                            width: 2  
                        }],  
                        polygonsPoints: parseTrajectoryPoints(trajectoryData, './assets/icon_map_start.png', './assets/icon_map_pass.png'),  
                    });  
                }  
                break;  
            }  
            case 'polygon': {  
                // 提取电子围栏信息，如果传递参数解析，否则从接口获取  
                const parsedPolygons = polygons || [];  
                let watch_electronic_fence_list = device_imei ?   
                    (await fetchDeviceInfo({ device_imei })).data.watch_electronic_fence_list || []   
                    : parsedPolygons;  
                if (watch_electronic_fence_list.length > 0) {  
                    this.setData({  
                        polygonsPoints: parseTrajectoryPoints(watch_electronic_fence_list, './assets/icon_map_start.png', './assets/icon_map_pass.png'),  
                        polygon: [{  
                            points: watch_electronic_fence_list.map(item => ({  
                                longitude: item.ele_fence_precision,  
                                latitude: item.ele_fence_latitude  
                            })),  
                            dashArray: [0, 0],  
                            strokeWidth: 2,  
                            strokeColor: '#000000',  
                            fillColor: 'rgba(0, 0, 0, .3)'  
                        }],  
                        longitude: watch_electronic_fence_list[0].ele_fence_precision,  
                        latitude: watch_electronic_fence_list[0].ele_fence_latitude  
                    });  
                } else {  
                    await setMapCenter();  
                }  
                break;  
            }  
            default:  
                break;  
        }  
    },
    getMapCenter() {
        return new Promise((resolve, reject) => {
            wx.getLocation({
                type: 'gcj02',
                success(r) {
                    resolve({
                        longitude: r.longitude,
                        latitude: r.latitude
                    })
                },
                fail(err) {
                    reject(err)
                }
            })
        })
    },
    onMapClick(e) {
        if (this.data.readonly) return;
        let {
            polygonsPoints
        } = this.data, {
            latitude,
            longitude
        } = e.detail;
        if (polygonsPoints.length == 0) {
            polygonsPoints.push({
                id: polygonsPoints.length,
                latitude,
                longitude,
                iconPath: './assets/icon_map_start.png',
                width: 20,
                height: 20
            })
        } else {
            polygonsPoints.push({
                id: polygonsPoints.length,
                latitude,
                longitude,
                iconPath: './assets/icon_map_pass.png',
                width: 20,
                height: 20
            })
        }

        this.setData({
            polygonsPoints,
            polyline: [{
                points: polygonsPoints.map(item => {
                    return {
                        latitude: item.latitude,
                        longitude: item.longitude
                    }
                }),
                color: '#000000',
                width: 2
            }]
        })
    },
    onComplete() {
        this.setData({
            polygon: [{
                points: this.data.polygonsPoints.map(item => {
                    return {
                        latitude: item.latitude,
                        longitude: item.longitude
                    }
                }),
                dashArray: [0, 0],
                strokeWidth: 2,
                strokeColor: '#000000',
                fillColor: 'rgba(0, 0, 0, .3)'
            }]
        })
    },
    // 清空围栏 
    onRemove(e) {
        this.setData({
            polygon: null,
            polygonsPoints: [],
            polyline: null
        })
    },
    // 撤销围栏
    onRevocation(e) {
        let {
            polygonsPoints,
            polygon
        } = this.data;
        if (polygon?.length) {
            this.setData({
                polygon: null
            })
        }
        polygonsPoints.pop();
        this.setData({
            polygonsPoints,
            polyline: [{
                points: polygonsPoints.map(item => {
                    return {
                        latitude: item.latitude,
                        longitude: item.longitude
                    }
                }),
                color: '#000000',
                width: 2
            }]
        })
    },
    onShowNotice() {
        this.setData({
            noticeShow: true
        })
    },
    onNoticeClose() {
        this.setData({
            noticeShow: false
        })
    },
    onSubmit() {
        const {
            polygon
        } = this.data;
        let points = polygon[0].points.map(item => {
            return `(${item.longitude},${item.latitude})`
        })
        const params = {
            points: points.join('，')
        }
        customRedirect({
            url: '/Device/pages/Bind/Verify/index',
            params
        })
    }
})